import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = store.getters.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error

    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const { success, message } = response.data // 这个data是axios内部
    if (success) {
      return response.data // 直接返回后端数据, 省略一层data
    } else {
      Message.error(message)
      console.log('error') // http状态码2xx, 但是逻辑错误
      return Promise.reject(new Error(message)) // 返回Promise错误的对象
    }
  },
  error => {
    console.log(error, '1')
    Message.error(error.response.data.message) // http状态码4xx
    if (error?.response?.data?.code === 10002) {
      this.$store.dispatch('user/logoutActions')
    } else {
      console.log('没进去')
    }
    return Promise.reject(error)
  }
)

export default service
